package com.itheima.sh;
import com.alibaba.fastjson.JSON;
import com.itheima.sh.esdemo.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ElasticSearchTest {
    RestHighLevelClient client;
    @Before
    public void  testInitClient() throws Exception{

        client=new RestHighLevelClient
                (RestClient.builder(new HttpHost("192.168.200.150",9200,"http")
                )
                );

    }
    @Test
    public void testCreateIndex() throws IOException {
        // 1.创建CreateIndexRequest对象，并指定索引库名称
        CreateIndexRequest request = new CreateIndexRequest("user");
        // 2.指定settings配置(可以默认)
        request.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 1)
        );
        // 3.指定mapping配置
        request.mapping(
                "{\n" +
                        "    \"properties\": {\n" +
                        "      \"id\": {\n" +
                        "        \"type\": \"long\"\n" +
                        "      },\n" +
                        "      \"name\":{\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      },\n" +
                        "      \"age\":{\n" +
                        "        \"type\": \"integer\"\n" +
                        "      },\n" +
                        "      \"gender\":{\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      },\n" +
                        "      \"note\":{\n" +
                        "        \"type\": \"text\",\n" +
                        "        \"analyzer\": \"ik_max_word\"\n" +
                        "      }\n" +
                        "    }\n" +
                        "  }",
                //指定映射的内容的类型为json
                XContentType.JSON);
        // 4.发起请求，得到响应（同步操作）
        CreateIndexResponse response = client.indices()
                .create(request, RequestOptions.DEFAULT);

        //打印结果
        System.out.println("response = " + response.isAcknowledged());
    }
    @Test
    public void testAddDocument() throws Exception{
        //1. 准备文档数据
        User user = new User(862L, "张三", 22, "1", "黑马117");
        //2. 创建IndexRequest对象，并指定索引库名称
        IndexRequest indexRequest = new IndexRequest("user");
        //3. 指定新增的数据的id
        indexRequest.id(user.getId().toString());
        //4. 将新增的文档数据变成JSON格式
        user.setAge(null);
        user.setName("???");
        String userJson = JSON.toJSONString(user);
        //5. 将JSON数据添加到IndexRequest中
        indexRequest.source(userJson, XContentType.JSON);
        //6. 发起请求，得到结果
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("indexResponse= "+response.getResult());

    }
    @Test
    public void testfindDocumentById() throws Exception{
        //1. 创建GetRequest 对象，并指定索引库名称、文档ID
        GetRequest getRequest = new GetRequest("user", "862");
        //2. 发起请求，得到结果
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
        //3. 从结果中得到source，是json字符串
        String sourceAsString = response.getSourceAsString();
        //4. 将JSON反序列化为对象
        User user = JSON.parseObject(sourceAsString, User.class);
        System.out.println(user);
    }
    @Test
    public void testDeleteDocumentById() throws IOException {
        // 1.创建DeleteRequest对象，指定索引库名称、文档ID
        DeleteRequest request = new DeleteRequest(
                "user",
                "862");
        // 2.发起请求
        DeleteResponse deleteResponse = client.delete(
                request, RequestOptions.DEFAULT);

        System.out.println("deleteResponse = " + deleteResponse.getResult());
    }


    @Test
    public void testBulkAddDocumentList() throws IOException {
        // 1.从数据库查询文档数据
        //第一步：准备数据源。本案例使用List来模拟数据源。
        List<User> users = Arrays.asList(
                new User(51L, "Rose", 18, "1", "Rose同学在传智播客学表演"),
                new User(52L, "Jack", 38, "1", "Jack同学在黑马学JavaEE"),
                new User(53L, "小红", 23, "0", "小红同学在传智播客学唱歌"),
                new User(54L, "小明", 20, "1", "小明同学在黑马学JavaSE"),
                new User(55L, "达摩", 33, "1", "达摩和尚在达摩院学唱歌"),
                new User(56L, "鲁班", 24, "1", "鲁班同学走在乡间小路上"),
                new User(57L, "孙尚香", 26, "0", "孙尚香同学想带阿斗回东吴"),
                new User(58L, "李白", 27, "1", "李白同学在山顶喝着酒唱着歌"),
                new User(59L, "甄姬", 28, "0", "甄姬同学弹奏一曲东风破"),
                new User(60L, "虞姬", 27, "0", "虞姬同学在和项羽谈情说爱")
        );
        // 2.创建BulkRequest对象
        BulkRequest bulkRequest = new BulkRequest();
        // 3.创建多个IndexRequest对象，并添加到BulkRequest中
        for (User user : users) {
            bulkRequest.add(new IndexRequest("user")
                    .id(user.getId().toString())
                    .source(JSON.toJSONString(user), XContentType.JSON)
            );
        }
        // 4.发起请求
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        System.out.println("status: " + bulkResponse.status());
    }
    @After
    public void closed(){
        if (client !=null){
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
